package cn.wbu.zyh.service.impl;

import cn.wbu.zyh.dto.FavoritesDTO;
import cn.wbu.zyh.entity.Favorites;
import cn.wbu.zyh.mapper.FavoritesMapper;
import cn.wbu.zyh.service.FavoritesService;
import cn.wbu.zyh.vo.FavoritesVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class FavoritesServiceImpl implements FavoritesService {
    @Autowired
    private FavoritesMapper favoritesMapper;
    @Override
    public FavoritesVO favorite(FavoritesDTO favoritesDTO) {
        Favorites favorites = new Favorites();
        BeanUtils.copyProperties(favoritesDTO, favorites);

        // 检查是否已收藏
        int count = favoritesMapper.countByUsernameAndArticleId(favoritesDTO.getUsername(), favoritesDTO.getArticleId());
        boolean isFavorite;
        if (count > 0) {
            // 如果已收藏，则取消收藏
            favoritesMapper.deleteFavorite(favorites);
            isFavorite = false;
        } else {
            // 如果未收藏，则添加收藏
            favoritesMapper.insertFavorite(favorites);
            isFavorite = true;
        }

        // 构建返回的 FavoritesVO 对象
        FavoritesVO favoritesVO = new FavoritesVO();
        favoritesVO.setArticleId(favoritesDTO.getArticleId());
        favoritesVO.setUsername(favoritesDTO.getUsername());
        favoritesVO.setCreatedTime(favorites.getCreatedTime());
        favoritesVO.setFavorite(isFavorite);

        return favoritesVO;
    }

    public boolean isFavorite(String username, Long articleId) {
        int count = favoritesMapper.countByUsernameAndArticleId(username, articleId);
        return count > 0;
    }
}
